<template>
  <div>
    <div class="tree">
      <Button type="primary" @click="cancel();typeName = '添加';isWrite = true;">添加</Button>
      <Button type="primary" @click="edit">编辑</Button>
      <Button type="error" @click="del">删除</Button>
      <Tree :data="deptList" @on-select-change="selectItem"></Tree>
      <!-- <Tree :data="data1" @on-select-change="selectItem"></Tree> -->
    </div>
    <div class="form" v-if="">
      <Card class="form-menu-set">
        <p  slot="title">{{typeName}}菜单</p>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120">
          <FormItem label="父节点" prop="parentId">
            <Input v-model="formValidate.parentId" disabled/>
          </FormItem>
          <FormItem label="菜单名称" prop="name">
            <Input v-model="formValidate.name" :disabled="!isWrite"/>
          </FormItem>
          <FormItem label="菜单图标">
            <Input v-model="formValidate.icon" :disabled="!isWrite"/>
          </FormItem>
          <!--<FormItem label="权限标识">
            <Input v-model="formValidate.permission" :disabled="!isWrite"/>
          </FormItem>-->
          <FormItem label="页面路由">
            <Input v-model="formValidate.href" :disabled="!isWrite"/>
          </FormItem>
          <FormItem label="是否在菜单中显示" prop="isShow">
            <Select clearable v-model="formValidate.isShow" :disabled="!isWrite" style="width:100%">
              <Option value="0">显示</Option>
              <Option value="1">隐藏</Option>
            </Select>
          </FormItem>
          <FormItem label="排序" prop="sort">
            <Input placeholder="请输入数字" v-model="formValidate.sort" :disabled="!isWrite"/>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="next">{{type}}</Button>
            <Button @click="cancel">取消</Button>
          </FormItem>
        </Form>
      </Card>
      <Card class="form-menu-set">
        <p slot="title" style="height: 25px;line-height: 25px;">按钮或资源<Button size="small" @click="formMenuDate={};showModal.addShow = true;showModal.type = '新增';formMenuDate.menuId = item.id" type="primary" style="float: right;">新增</Button></p>
        <Table ref="selection" width="100%" :columns="listTitle" :data="list" :loading="loading" @on-selection-change="selectItem" ></Table>
      </Card>
    </div>
    <!--新增/编辑-->
    <Modal
      v-model="showModal.addShow"
      :title="showModal.type"
      :closable="true"
      :style="{textAlign:'left'}">
      <Form ref="formMenuDate" :model="formMenuDate" :rules="ruleMenuDate" :label-width="80">
        <FormItem label="资源名称" prop="name">
          <Input v-model="formMenuDate.name" />
        </FormItem>
        <FormItem label="排序" prop="sort">
          <Input v-model="formMenuDate.sort" />
        </FormItem>
        <FormItem label="菜单ID" prop="menuId">
          <Input v-model="formMenuDate.menuId" disabled/>
        </FormItem>
        <FormItem label="链接" prop="href">
          <Input v-model="formMenuDate.href" />
        </FormItem>
        <FormItem label="是否启用" prop="delFlag">
          <Select clearable v-model="formMenuDate.delFlag" placeholder="请选择" style="width:150px">
            <Option v-for="item in delFlagList" :value="item.id" :key="item.id">{{item.name}}</Option>
          </Select>
        </FormItem>
      </Form>
      <div style="margin-left: 350px;">
        <Button @click="close">取消</Button>
        <Button type="primary" @click.prevent="handleBtn">确定</Button>
      </div>
    </Modal>
    <confirm-dialog :show="showModal" @confirm="deleteItem" @cancel="showModal.isShow = false"></confirm-dialog>
  </div>
</template>

<script>
  import confirmDialog from '../../template/confirmDialogTemplate'
  export default {
    components: {
      confirmDialog
    },
    data () {
      return {
       tag: {
          'title': '菜单管理',
          'path': '/work/menu/list'
        },
        list:[],
        delFlagList: [// 0启用 1禁用
          {
            id: '0',
            name: '启用'
          },
          {
            id: '1',
            name: '禁用'
          }
        ],
        loading: true,
        typeName:'',
        formMenuDate: {
          name: '',
          sort: '',
          menuId: '',
          href: '',
          delFlag: '',

        },
        formValidate: {
          parentId: '',
          parentIds: [],
          name: '',
          icon: '',
          permission: '',
          href: '',
          type: '',
          sort: ''
        },
        ruleValidate: {
          name: [
            { required: true, message: '请填写菜单名称', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择类型', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '请填写排序', trigger: 'blur' }
          ],
          isShow: [
            { required: true, message: '请选择', trigger: 'blur' }
          ]
        },
        ruleMenuDate: {
          name: [
            { required: true, message: '请填写资源名称', trigger: 'blur' }
          ],
          delFlag: [
            { required: true, message: '请选择类型', trigger: 'blur' }
          ],
          /*sort: [
            { required: true, message: '请填写排序', trigger: 'blur' }
          ]*/
        },
        deptList: [],
        isWrite: false,
        item: {},
        showModal: {
          isShow: false,
          addShow:false,
          type:'新增'
        },
        type: '提交',
        listTitle:[
          {
            title: '资源名称',
            key: 'name',
            align:'center',
          },
          {
            title: '状态',
            key: 'delFlag',
            align:'center',
            render: (h, params) => {
              let text = '';
              if(params.row.delFlag == '0'){
                text = '启用';
                return h('div', [
                  h('Button', {
                    props: {
                      type: 'success',
                      size: 'small'
                    }
                  },text)
                ])
              }else{
                text = '禁用'
                return h('div', [
                  h('Button', {
                    props: {
                      type: 'warning',
                      size: 'small'
                    }
                  },text)
                ])
              }

            }
          },
          {
            title: '操作',
            key: 'action',
            align:'center',
            //width: 150,
            render: (h, params) => {
              let text = '';
              let delFlag = '';
              if(params.row.delFlag == '1'){
                text = '启用';
                delFlag = '0';
              }else{
                text = '禁用'
                delFlag = '1';
              }
              return h('div', [
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showModal.addShow = true;
                      this.showModal.type = '编辑';
                      //this.show(params.index)
                      this.formMenuDate = params.row;
                      console.log(params)
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: `<p>是否${text}当前资源?</p>`,
                        onOk: () => {
                          this.showModal.type = '编辑';
                          this.formMenuDate = {};
                          this.formMenuDate.token = sessionStorage.getItem('token');
                          this.formMenuDate.delFlag = delFlag;
                          this.formMenuDate.id = params.row.id;

                          this.handleBtn();
                        },
                        onCancel: () => {
                        }
                      });
                      //this.remove(params.index)
                    }
                  }
                }, text)
              ]);
            }
          },
        ]
      }
    },
    mounted () {
      this.getTree();
      this.$store.commit('changeTag', this.tag.path);
      this.$store.commit('openPage', this.tag);
    },
    methods: {
      getTree(){
        this.loading = true;
        this.$post('/sysMeun/list',{token:sessionStorage.getItem('token')})
          .then((res) => {
            this.loading = false;
            console.log(JSON.parse(res.data),'sysList');
            const getTree = arr => arr.map(item => ({
              id: item.id,
              name: item.name,
              title: item.name,
              parentId: item.parentId,
              label: item.name,
              children: getTree(item.childrens),
            }))
            this.deptList = getTree(JSON.parse(res.data));
            console.log(this.deptList,'deptList')
          }, (err) => {
            console.log(err);
          })
      },
      selectNode(current,group){
        console.log(current,'current');
        console.log(group,'group');
      },
      selectItem(value){
        console.log(value,'value')
        if(value.length > 0){
          //this.cancel();
          value = value[0];
          this.item = {
            id: value.id,
            name: value.name,
            icon: value.icon,
            href: value.href,
            type: value.type,
            sort: value.sort
          };
          this.getNodeDate(this.item.id)
        }
      },
      getNodeDate(nodeDate){
        this.loading = true;
        this.$post('/sysMeun/getById',{id:nodeDate,token:sessionStorage.getItem('token')})
          .then((res) => {
            if(res.code === 0){
              this.loading = false;
              console.log(res.data,'getNodeDate')
              let sysMeunDBO = res.data.sysMeunDBO;
              if(sysMeunDBO.parentId === 0){
                this.item.parentIds = [];
              }else{
                this.item.parentIds = sysMeunDBO.parentIds.split(',').map(item => parseInt(item));
              }
              this.item.name = sysMeunDBO.name;
              this.item.icon = sysMeunDBO.icon;
              this.item.parentId = sysMeunDBO.parentId;
              this.item.href = sysMeunDBO.href;
              this.item.type = sysMeunDBO.type;
              this.item.isShow = sysMeunDBO.isShow;
              this.item.sort = sysMeunDBO.sort.toString();
              this.formValidate = { ...this.item}
              this.list = res.data.sysMeunFuncDBO;
            }else{
              this.$Message.error(res.msg);
            }
          },(err) => {
            console.log(err);
          })
      },
      edit(){
        this.typeName = '编辑';
        console.log(this.item);
        if(Object.keys(this.item).length == 0){
          this.$Message.warning('当前未选中！');
          return false;
        }
        this.type = '修改';
        this.isWrite = true;
        this.getNodeDate(this.item.id);
      },
      del(){
         if(Object.keys(this.item).length == 0){
          this.$Message.warning('当前未选中！');
          return false;
        }
        this.showModal.isShow = true;
      },
      deleteItem(){
        this.$post('/sysMeun/discard', {id: this.item.id})
          .then((res) => {
            if(res.code === 0){
              this.$Message.success('删除成功！');
              this.getTree();
              this.$emit('menulist');
              this.item = {};
              // this.formRole ={}
            }else{
              // this.$Message.error(res.msg);
            }
          }, (err) => {
            console.log(err);
            this.item = {};
          })
      },
      next(){
        this.$refs['formValidate'].validate((valid) => {
          if (valid) {
            let params = {
              //parentIds: this.formValidate.parentIds.length === 0 ? -1 : this.formValidate.parentIds[this.formValidate.parentIds.length-1],
              name: this.formValidate.name,
              icon: this.formValidate.icon,
              parentId: this.formValidate.parentId,
              href: this.formValidate.href,
              sort: this.formValidate.sort,
              isShow: this.formValidate.isShow,
              token: sessionStorage.getItem('token')
            };
            params = JSON.parse(JSON.stringify(params));
            if(this.type === '提交'){
              this.$post('/sysMeun/append',params)
                .then((res) => {
                  if(res.code === 0){
                    this.$Message.success('添加成功！');
                    this.getTree();
                    this.$emit('menulist','我是菜单');
                    this.cancel();
                  }else{
                    // this.$Message.error(res.msg);
                  }
                }, (err) => {
                  console.log(err);
                })
            }else{
              params.id = this.item.id;
              this.$post('/sysMeun/modify',params)
                .then((res) => {
                  if(res.code === 0){
                    this.$Message.success('修改成功！');
                    this.getTree();
                    this.$emit('menulist');
                    this.cancel();
                  }else{
                    // this.$Message.error(res.msg);
                  }
                }, (err) => {
                  console.log(err);
                })
            }

          } else {

            this.$Message.error('请正确填写信息！');
          }

        })
      },
      cancel(){
        //  if(Object.keys(this.item).length == 0){
        //   this.$Message.warning('当前未选中！');
        //   return false;
        // }
        this.formValidate = {
          parentIds: this.formValidate.parentIds,
          parentId: this.formValidate.id,
          name: '',
          id:'',
          icon: '',
          href: '',
          sort: ''
        };
        this.item = {};
        this.isWrite = false;
        this.type = '提交';
        this.$refs['formValidate'].resetFields()

      },
      format (labels) {
        const index = labels.length - 1;
        return labels[index];
      },
      handleBtn(){
        let url = '';
        let params = {};
        this.$refs['formMenuDate'].validate((valid) => {
          if(valid){
            params = this.formMenuDate;
            params.token = sessionStorage.getItem('token');
            if (this.showModal.type == '编辑') {
              url = '/sysButton/modify';
            } else {
              url = '/sysButton/append'
            }

            this.$post(url, params)
              .then((res) => {
                if (res.code === 0) {
                  this.$Message.success(`${this.showModal.type}成功！`);
                  this.getNodeDate(this.item.id);
                } else {
                  // this.$Message.error(res.msg);
                }
              }, (err) => {
                console.log(err);
              })


          }


        })
      },
      close() {
        this.showModal.addShow = false;
        this.$refs['formMenuDate'].resetFields()
      }

    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .form{
    float: left;
    margin-left: 30px;
    width: 50%;
    min-width:500px;
  }
  .form-menu-set{
    padding:0 30px;
    background: #fff;
    margin-bottom: 30px;
    box-shadow: 0 2px 5px 2px #ccc;

  }
  .tree{
    float: left;
    width:20%;
    min-width: 300px;
    background: #fff;
    padding: 30px;
    box-shadow: 0 2px 5px 2px #ccc;
  }
  /deep/ .ivu-form-item-content{
    width:300px;
  }
  /deep/ .ivu-modal-footer{
    display: none;
  }
</style>
